package com.zhentao.ws;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 学生端WS会话管理器：按userKey保存连接
 */
public class WebSocketSessionManager {
    private static final ConcurrentHashMap<String, WebSocketSession> SESSIONS = new ConcurrentHashMap<>();

    public static String buildKey(Integer userType, Long userId) {
        return userType + ":" + userId;
    }

    public static void put(String key, WebSocketSession session) {
        SESSIONS.put(key, session);
    }

    public static void remove(String key) {
        SESSIONS.remove(key);
    }

    public static boolean sendTo(Integer userType, Long userId, String payload) {
        String key = buildKey(userType, userId);
        WebSocketSession session = SESSIONS.get(key);
        if (session == null || !session.isOpen()) return false;
        try {
            session.sendMessage(new TextMessage(payload));
            return true;
        } catch (IOException e) {
            return false;
        }
    }
}